package com.imhuis.pay.wxpay;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

@Configuration
public class WxPayConfig {

    /**
     * 构造HttpClient
     *
     * @param mchId       商户号
     * @param apiV3Key    V3秘钥
     * @param mchSerialNo 证书序列号
     * @param privateKey  证书私钥
     * @return HttpClient
     */
    private CloseableHttpClient httpClientBuilder(String mchId, String apiV3Key, String mchSerialNo, PrivateKey privateKey) {
        // 不需要传入微信支付证书，将会自动更新
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, privateKey)),
                apiV3Key.getBytes(StandardCharsets.UTF_8));

        return WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, mchSerialNo, privateKey)
                .withValidator(new WechatPay2Validator(verifier))
                .build();
    }

    @Bean
    public HttpClient httpClient(){
        ClassPathResource classPathResource = new ClassPathResource("/*.pem");
        PrivateKey merchantPrivateKey = null;
        try {
            merchantPrivateKey = PemUtil.loadPrivateKey(classPathResource.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpClientBuilder("", "", "", merchantPrivateKey);
    }

}
